<?php
/**
 * 21天减重测评算法
 * Created by PhpStorm.
 * User: liao
 * Date: 2016/12/12
 * Time: 16:41
 */

namespace App\Services\Result;

use App\Interf\Resultable;
use Monolog\Logger;
use TestingConfig;
use ParamConfig;
use App\Models\LogHelper;

class FourteenDecWeightResult extends BaseResult implements Resultable
{
    private $answers;
    /**肥胖指数*/
    private $fatFactorAttrObj;
    /**身体概述*/
    private $bodySummaryAttrObj;
    /**健康指数*/
    private $healthFactorAttrObj;
    /**减重阻力*/
    private $dwResistAttrObj;

    public function __construct($answersStr = null)
    {
        $this->answers = $this->convertAnswer($answersStr);
        $this->fatFactorAttrObj = $this->configAttrObj(1,'肥胖指数');
        $this->bodySummaryAttrObj = $this->configAttrObj(2,'身材概述');
        $this->healthFactorAttrObj = $this->configAttrObj(3,'健康指数');
        $this->dwResistAttrObj = $this->configAttrObj(4,'减重阻力');
    }

    public function result()
    {
//        $attrs = [];
//        $index = 27;
//        $answerWeight = 5;
//        $result = $this->getItemResult($index,$answerWeight);
//        return $result;
        $attrs = [];
        /*减肥指数*/
        array_push($attrs,$this->getFatAttr());
        /*身材概述*/
        array_push($attrs,$this->getBodySummaryAttr());
//        /**健康指数*/
        array_push($attrs,$this->getHealthAttr());
//        /**减重阻力*/
        array_push($attrs,$this->getDecreaseResistanceAttr());

        $data['attrs'] = $attrs;
        //$data['chatparam'] = $this->getChatparam();
        $data['chatparam'] = "";
        //图类型常规图
        $data['chatType'] = $this->getChatType();
        return $data;

    }


    /**
     * 肥胖指数
     */
    protected function getFatAttr(){
        $note = '';
        //第一部分的结论
        $note .= $this->getFatResultFirstNote();
        $this->getNoteByIndex($note,22);
        //获取额外部分
        $extra = null;
        $this->getNutriContact($note);
        $obj = $this->fatFactorAttrObj;
        $obj = $this->compactAttrObj($obj['attr_id'],$obj['title'],$note,$extra);
        LogHelper::log('14days - fat waist result ====>');
        LogHelper::log($obj);
        return $obj;
    }


    /**
     * 身材概述
     */
    protected function getBodySummaryAttr(){
        $note = '';
        //第五道题
        $this->getNoteByIndex($note,5);
        LogHelper::log('index 5 note');
        LogHelper::log($note);
        //获取第六道题
        $itemSixObj = $this->getDefaultAnswerObjByIndex(6);
        $itemSixObjTitle = ParamConfig::getValue('FW.resist.item.6.start');
        //替换数据口中的@6，显示血型
        $itemSixObjTitle = str_replace('@6',$itemSixObj['answer'],$itemSixObjTitle);
        //拼接第六道题的描述
        $note .= $itemSixObjTitle.'<br/>';
        //第6道
        $this->getNoteByIndex($note,6);
        $this->getNutriContact($note);
        $obj = $this->bodySummaryAttrObj;
        $obj = $this->compactAttrObj($obj['attr_id'],$obj['title'],$note);
        return $obj;
    }



    /**
     * 健康指数
     */
    protected function getHealthAttr(){
        $note = '';
        //第25道题
        $this->getNoteByIndex($note,26);
        //第26道题
        $this->getNoteByIndex($note,27);

        $answer17 = $this->getDefaultAnswerObjByIndex(17);
        if($answer17['weight']>0){
            //额外的健康因素
            $itemExtraTitleObj = ParamConfig::getValue('FW.health.life.extra.title');
            $note .= $itemExtraTitleObj;
            //第17道题
            $this->getNoteByIndex($note,17);
        }

        LogHelper::log('14days-getHealthAttr note=======>');
        LogHelper::log($note);

        $this->getNutriContact($note);
        $obj = $this->healthFactorAttrObj;
        $obj = $this->compactAttrObj($obj['attr_id'],$obj['title'],$note);
        return $obj;
    }


    /**
     * 减重阻力
     */
    protected function getDecreaseResistanceAttr(){
        $note = '';
        //第27道题
        $this->getNoteByIndex($note,28);
        //获取第18道题
        $itemNineteenObj = $this->getDefaultAnswerObjByIndex(18);
        if(intval($itemNineteenObj['weight'])>0){
            $itemNinteenObjTitleObj = ParamConfig::getValue('FW.resist.item.18');
            $note .= $itemNinteenObjTitleObj;
        }
        //第10道题
        $this->getNoteByIndex($note,10);
        //第18道题
        $this->getNoteByIndex($note,14);

        $this->getNutriContact($note);

        $obj = $this->dwResistAttrObj;
        $obj = $this->compactAttrObj($obj['attr_id'],$obj['title'],$note);
        return $obj;
    }

    protected function getNutriContact(&$note){
        $note .= ParamConfig::getValue('FW.resist.item.14.result');
    }

    /**
     * 获取单个问题通过条件判断后最终的结果
     */
    protected function getItemResult($index,$answerWeight){
        $result = '';
        $values = $this->getSingleItemConfig($index);
        if(count($values)>0){
            foreach ($values as $val){
                $expression = $val['key'];
                if($data = $this->getQuestionItemCondResult($expression,$answerWeight)){
                    $result = $val['value'];
                    break;
                }
            }
        }
        return $result;
    }


    protected function getNoteByIndex(&$note,$index){
        $obj = $this->getDefaultAnswerObjByIndex($index);
        $note .= $this->getItemResult($obj['index'],$obj['weight']);
    }


    /**
     * 获取腰围的结果
     */
   /* protected function getFatWaistResult(){
        $fatWaistResults = TestingConfig::getDWTestingFatWaistResult();
        $answer3 = $this->getDefaultAnswerObjByIndex(3);
        $answer4 = $this->getDefaultAnswerObjByIndex(4);
        $answer24 = $this->getDefaultAnswerObjByIndex(24);
        $answer23 = $this->getDefaultAnswerObjByIndex(23);
        $data = '';
        if(count($fatWaistResults)>0){
            foreach ($fatWaistResults as $result){
                $key = $result['key'];
                //现替换表达式中的值 ，表达式原型为@3==0 && @24==2
                $key = str_replace('@3',$answer3['weight'],$key);
                $key = str_replace('@23',$answer23['weight'],$key);
                $key = str_replace('@24',$answer24['weight'],$key);
                //在将表达式赋值为val变量，并通过eval函数进行运算得出val的值
                $val = '$val='.$key.';';
                LogHelper::log('fat waist expression===>');
                LogHelper::log($val);
                LogHelper::log('reslut===>');
                LogHelper::log($result);
                eval($val);
                if($val){
                    $data = str_replace('$4',$answer4['answer'],$result['value']);
                    break;
                }
            }
        }
        LogHelper::log('fat waist data===>');
        LogHelper::log($data);
        return $data;
    }*/


    protected function getFatResultExtraPart(){
        $part1['key'] = TestingConfig::getValue('DW.fat.question.title');
        $part1['value'] = TestingConfig::getValue('DW.fat.question.answer');
        $data['part1'] = $part1;
        return $data;
    }


    /**
     * 图标对应的BMI数据
     */
    protected function getChatparam(){
        $data = [];
        $obj['key'] = 'BMI';
        $answer21 = $this->getDefaultAnswerObjByIndex(21);
        $obj['value'] = round(doubleval($answer21['weight']),2);
        array_push($data,$obj);
        return $data;
    }


    /**
     * 获取肥胖指数第一个结论部分
     */
    protected function getFatResultFirstNote(){
        $result = ParamConfig::getValue('FW.fat.result.first.note');
        $answer19 = $this->getDefaultAnswerObjByIndex(19);
        $answer29 = $this->getDefaultAnswerObjByIndex(29);
        $result = str_replace('$19',$answer19['answer'],$result);
        $result = str_replace('@29',round($answer29['weight'],2).'%',$result);
        return $result;
    }

    protected function compactAttrObj($id,$title,$note,$extra=''){
        return [
            'attr_id' => $id,
            'title' => $title,
            'note' => $note,
            'extra' =>$extra
        ];
    }

    protected function getDefaultAnswerObjByIndex($index){
        $obj = [];
        foreach ($this->answers as $answer){
            if($index == $answer['index']){
                $obj = $answer;
                break;
            }
        }
        return $obj;
    }


    /**
     * 组装结果集
     */
    protected function compactResults($itemList){
        $results = [];
        if(count($itemList)>0){
            foreach ($itemList as $item){
                if($result = $this->getItemResult($item['index'],$item['value'])){
                    array_push($results,$result);
                }
            }
        }
        return $results;
    }






    /**
     * 获取单个题目对应的条件判断值
     */
    protected function getQuestionItemCondResult($expression,$originVal){
        $expression = $expression.'?1:0;';
        $result = $this->compactExpress($expression,$originVal);
        return $result;
    }

    /**
     * 组装表达式,这里充分的利用eval函数可以计算的功能
     * @param string $expression 原始表达式
     * @param string $orgVal 原始值
     * @return string
     */
    protected function compactExpress($expression, $orgVal){
        $val = '$val=$orgVal;$val='.$expression;
        eval($val);
        return $val;
    }


    /**
     * 获取减重测评单个题目对应的配置信息
     */
    protected function getSingleItemConfig($index){
        $values = ParamConfig::getDWTestingValuesByTag($index);
        return $values;
    }



    /**将answer转换为数组
     * @param $answerStr
     * @return array
     */
    protected function convertAnswer($answerStr){
        LogHelper::log('FINAL ANSWER STR============>');
        LogHelper::log($answerStr);
        $answers = [];
        $answerArr = explode('##',$answerStr);
        if(count($answerArr)>0){
            foreach ($answerArr as $answer){
                $singleArr = explode(':',$answer);
                if(count($singleArr)>0){
                    $obj['index'] = $singleArr[0];
                    $obj['weight'] = $singleArr[1];
                    $obj['answer'] = $singleArr[2];
                    array_push($answers,$obj);
                }
            }
        }
        return $answers;
    }

}